package io.renren.modules.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.modules.app.annotation.BimLogin;
import io.renren.modules.app.dao.BimUserDao;
import io.renren.modules.app.entity.BimRequestEntity;
import io.renren.modules.app.entity.BimUserEntity;
import io.renren.modules.app.service.BimRequestService;
import io.renren.modules.app.service.BimUserService;
import io.renren.modules.app.utils.BimR;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import java.util.List;



/**
 * ${comments}
 *
 * @author lmzhu
 * @email zhulimingchina@gmail.com
 * @date 2020-08-13 10:53:17
 */
@RestController
@RequestMapping("app/bimuser")
public class BimUserController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BimUserService bimUserService;

    @Autowired
    private BimRequestService bimRequestService;

    @Autowired
    private BimUserDao bimUserDao;

    @Value("${bim.schema}")
    private String schemaStr;
    /**
     * 列表
     */
    @RequestMapping("/SchemaService")
    public BimR schema(@RequestBody String body) {
        logger.info("BIM推送数据-{}:{}",Thread.currentThread().getStackTrace()[1].getMethodName(),body);
        BimRequestEntity bimRequestEntity = JSON.parseObject(body,BimRequestEntity.class);
        String bimRequestId = bimRequestEntity.getBimRequestId();
        try {
            bimRequestService.checkAccount(bimRequestEntity);
            JSONObject schemaJson = JSONObject.parseObject(schemaStr);
            return BimR.ok(schemaJson).put("bimRequestId",bimRequestId);
        } catch (RuntimeException e) {
            String errMsg = e.getMessage();
            logger.error(errMsg);
            return BimR.error(errMsg).put("bimRequestId",bimRequestId);
        }

    }


    /**
     * 保存
     */
    @RequestMapping("/UserCreateService")
    @BimLogin
    public BimR userCreate(@RequestBody String body){
        logger.info("BIM推送数据-{}:{}",Thread.currentThread().getStackTrace()[1].getMethodName(),body);
        BimUserEntity bimUser = JSON.parseObject(body,BimUserEntity.class);
        BimRequestEntity bimRequest = JSON.parseObject(body,BimRequestEntity.class);
        String bimRequestId = bimRequest.getBimRequestId();
        try {
            bimRequestService.checkAccount(bimRequest);
            ValidatorUtils.validateEntity(bimUser, AddGroup.class);
            bimUserService.save(bimUser);
            logger.debug("BIM用户保存成功:{}",bimUser);
            return BimR.ok().put("uid",bimUser.getId()).put("bimRequestId",bimRequestId);
        } catch (RuntimeException e) {
            String errMsg = e.getMessage();
            logger.error(errMsg);
            if(e instanceof DuplicateKeyException){
                errMsg = "数据库中已存在该记录";
            }
            return BimR.error(errMsg).put("bimRequestId",bimRequestId);
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/UserUpdateService")
    public BimR userUpdate(@RequestBody String body){
        logger.info("BIM推送数据-{}:{}",Thread.currentThread().getStackTrace()[1].getMethodName(),body);
        BimUserEntity bimUser = JSON.parseObject(body,BimUserEntity.class);
        BimRequestEntity bimRequest = JSON.parseObject(body,BimRequestEntity.class);
        String bimRequestId = bimRequest.getBimRequestId();
        try {
            bimRequestService.checkAccount(bimRequest);
            bimUser.setId(bimRequest.getBimUid());
            Number update = 0;
            if(bimUserService.updateById(bimUser)){
                update = 1;
                logger.info("BIM用户更新成功:{}",bimUser);
            }
            return BimR.ok().put("bimRequestId",bimRequestId);
        } catch (RuntimeException e) {
            String errMsg = e.getMessage();
            logger.error(errMsg);
            if(e instanceof DuplicateKeyException){
                errMsg = "数据库中已存在该记录";
            }
            return BimR.error(errMsg).put("bimRequestId",bimRequestId);
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/UserDeleteService")
    public BimR userDelete(@RequestBody String body){
        logger.info("BIM推送数据-{}:{}",Thread.currentThread().getStackTrace()[1].getMethodName(),body);
        BimRequestEntity bimRequestEntity = JSON.parseObject(body,BimRequestEntity.class);
        String bimRequestId = bimRequestEntity.getBimRequestId();
        try {
            bimRequestService.checkAccount(bimRequestEntity);
            String id = bimRequestEntity.getBimUid();
            Number update = 0;
            if(bimUserService.removeById(id)){
                update = 1;
                logger.info("BIM用户删除成功:{}",id);
            }
            return BimR.ok().put("bimRequestId",bimRequestId);
        } catch (RuntimeException e) {
            String errMsg = e.getMessage();
            logger.error(errMsg);
            if(e instanceof DataAccessException){
                errMsg = "数据库错误";
            }
            return BimR.error(errMsg).put("bimRequestId",bimRequestId);
        }
    }

    /**
     * 返回所有ids
     */
    @RequestMapping("/QueryAllUserIdsService")
    public BimR queryAllUserIds(@RequestBody String body){
        logger.info("BIM推送数据-{}:{}",Thread.currentThread().getStackTrace()[1].getMethodName(),body);
        BimRequestEntity bimRequestEntity = JSON.parseObject(body,BimRequestEntity.class);
        String bimRequestId = bimRequestEntity.getBimRequestId();
        try {
            bimRequestService.checkAccount(bimRequestEntity);
            List<String> userIdList = bimUserDao.queryAllUserIds();
            return BimR.ok().put("userIdList", userIdList).put("bimRequestId",bimRequestId);
        } catch (RuntimeException e) {
            String errMsg = e.getMessage();
            logger.error(errMsg);
            if(e instanceof DataAccessException){
                errMsg = "数据库错误";
            }
            return BimR.error(errMsg).put("bimRequestId",bimRequestId);
        }
    }


    /**
     * 根据id查用户
     */
    @RequestMapping("/QueryUserByIdService")
    public BimR queryUserById(@RequestBody String body){
        logger.info("BIM推送数据-{}:{}",Thread.currentThread().getStackTrace()[1].getMethodName(),body);
        BimRequestEntity bimRequestEntity = JSON.parseObject(body,BimRequestEntity.class);
        String bimRequestId = bimRequestEntity.getBimRequestId();
        try {
            bimRequestService.checkAccount(bimRequestEntity);
            BimUserEntity account = bimUserService.getById(bimRequestEntity.getBimUid());
            return BimR.ok().put("account", account).put("bimRequestId",bimRequestId);
        } catch (RuntimeException e) {
            String errMsg = e.getMessage();
            logger.error(errMsg);
            if(e instanceof DataAccessException){
                errMsg = "数据库错误";
            }
            return BimR.error(errMsg).put("bimRequestId",bimRequestId);
        }
    }


}
